package com.gtc.zsk.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.gtc.zsk.common.ErrorCode;
import com.gtc.zsk.config.PayConfig;
import com.gtc.zsk.exception.BusinessException;
import com.gtc.zsk.model.vo.PayVO;
import net.bytebuddy.implementation.bytecode.Throw;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


public class PayUtil {


    public PayVO sendPayment(String out_trade_no, String name, float money, String param, String type, long questionBankId) {
        //pid={商户ID}&type={支付方式}&out_trade_no={商户订单号}&notify_url={服务器异步通知地址}&return_url={页面跳转通知地址}&name={商品名称}&money={金额}&clientip={用户IP地址}&device={设备类型}&sign={签名字符串}&sign_type=MD5
        //[clientip, device, money, name, notify_url, out_trade_no, pid, return_url, sign_type, type]
        String mdString = "clientip=" + PayConfig.clientip + "&device=" + PayConfig.device + "&money=" + money + "&name=" + name + "&" +
                "notify_url=" + PayConfig.notify_url + "&out_trade_no=" + out_trade_no + "&param=" + param + "&pid=" + PayConfig.pid + "&return_url=" + PayConfig.return_url + questionBankId +
                "&type=" + type + PayConfig.key;
        //请求参数md5加密后得到签名
        String sign = MD5Util.GetMD5Code(mdString);
        //封装请求参数
        Map<String, Object> map = new HashMap<>();
        map.put("clientip", PayConfig.clientip);
        map.put("device", PayConfig.device);
        map.put("money", money);
        map.put("name", name);
        map.put("notify_url", PayConfig.notify_url);
        map.put("out_trade_no", out_trade_no);
        map.put("param", param);
        map.put("pid", PayConfig.pid);
        map.put("return_url", PayConfig.return_url + questionBankId);
        map.put("sign_type", PayConfig.sign_type);
        map.put("type", type);
        map.put("sign", sign);
        String body = HttpUtil.post(PayConfig.url, map);
        Gson gson = new Gson();
        PayVO payVO = null;
        try {
            payVO = gson.fromJson(body, PayVO.class);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "操作失败，请联系管理员（微信号：gtc4Real）！");
        }
        return payVO;

    }
}